package nz.ac.massey.cs.pp.swing101.tree;

import java.io.File;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class FileSystemTreeModel implements TreeModel {

	@Override
	public Object getRoot() {
		return new File(".");
	}

	@Override
	public Object getChild(Object parent, int index) {
		File file = (File)parent;
		return file.listFiles()[index];
	}

	@Override
	public int getChildCount(Object parent) {
		File file = (File)parent;
		return file.listFiles().length;
	}

	@Override
	public boolean isLeaf(Object node) {
		File file = (File)node;
		return !file.isDirectory();
	}

	@Override
	public void valueForPathChanged(TreePath path, Object newValue) {}

	@Override
	public int getIndexOfChild(Object parent, Object child) {
		File folder = (File)parent;
		File file = (File)child;
		for (int i=0;i<folder.listFiles().length;i++) {
			if (folder.listFiles()[i].equals(child)) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public void addTreeModelListener(TreeModelListener l) {}

	@Override
	public void removeTreeModelListener(TreeModelListener l) {}



}
